package com.johnny.myRedis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

public class MyRedisTransaction {
    Jedis jedis;

    MyRedisTransaction() {
        this.jedis = new Jedis("192.168.99.100", 6379); //dockerIP地址
        jedis.auth("654321");
    }

    public Jedis getJedis() {
        return jedis;
    }


    public void transaction1() {
        Transaction transaction = this.jedis.multi();
        transaction.set("balance", "100");
        transaction.set("debt","0");
        transaction.exec();
        //transaction.discard();//放弃执行
    }

    public boolean transMethod() {
        int balance; //可用余额
        int debt;//欠款
        int amtToSubtract=10;//实刷额度

        jedis.watch("balance"); //监控
        //jedis.set("balance","5")  模拟其他程序已经修改了该条目
        balance = Integer.parseInt(jedis.get("balance"));
        if(balance < amtToSubtract){
            jedis.unwatch();
            System.out.println("modify");
            return false;
        }else{
            System.out.println("************transaction");
            Transaction transaction = jedis.multi();
            transaction.decrBy("balance",amtToSubtract);
            transaction.incrBy("debt",amtToSubtract);
            transaction.exec();
            balance = Integer.parseInt(jedis.get("balance"));
            debt = Integer.parseInt(jedis.get("debt"));
            System.out.println("**********"+balance);
            System.out.println("**********"+debt);
            return true;
        }

    }


    public static void main(String[] args) {
        MyRedisTransaction mt = new MyRedisTransaction();
        boolean retValue = mt.transMethod();
        System.out.println("main retValue-------:" + retValue);
    }
}
